package de.cbf.cam.dsa.exchange.heldenrmi.preferences;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;

import de.cbf.cam.dsa.exchange.heldenrmi.Activator;

/**
 * Class used to initialize default preference values.
 */
public class PreferenceInitializer extends AbstractPreferenceInitializer {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
	 */
	public void initializeDefaultPreferences() {
		IPreferenceStore store = Activator.getDefault().getPreferenceStore();
		//get path from file "dsa4.properties" in user home
		String propFileName = "\\.dsa4.properties";			
		String propertiesFile = System.getProperty("user.home")+propFileName;
		
		String path = readPathFromPropFile(propertiesFile);
		
		store.setDefault(PreferenceConstants.P_PathHeldenJAR,	 path);
		store.setDefault(PreferenceConstants.P_Launch_Server, 	 true);
		store.setDefault(PreferenceConstants.P_RMIServerIP,		"localhost");
		store.setDefault(PreferenceConstants.P_RMIServerPort,	"10099");
		store.setDefault(PreferenceConstants.P_RMIServerName,	"RmiHeldenServer");
	}

	private String readPathFromPropFile(String propertiesFile) {
		String attributePath 		= "helden4_1.path=";
		String attributeFileName 	= "helden4_1.file=";
		String dir  = "";
		String file = "";
		File propFile = new File(propertiesFile);
		try {
			FileInputStream is = new FileInputStream(propFile);
			InputStreamReader reader =  new InputStreamReader(is);
			BufferedReader bufferedReader = new BufferedReader(reader);
			
			String line = "";
			while(bufferedReader.ready()){
				line = bufferedReader.readLine();
				
				if(line.startsWith(attributePath)){
					//found correct attribute
					dir = line.substring(attributePath.length());					
				}
				if(line.startsWith(attributeFileName)){
					//found correct attribute
					file = line.substring(attributeFileName .length());					
				}
			}	
			bufferedReader.close();
			reader.close();
			is.close();
		} catch (IOException e) {			
			e.printStackTrace();
		}
		String path = dir+"\\"+file;
		//path "beautification"
		path = path.replace("\\:/",":\\");
		path = path.replace("/","\\");
		return path;
	}
}
